package com.example.project7.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.example.project7.BookManagerActivity;
import com.example.project7.InterestSelectActivity;
import com.example.project7.LoginActivity;
import com.example.project7.R;
import com.example.project7.utils.AvatarManager;
import java.io.IOException;
import java.io.InputStream;

public class MineFragment extends Fragment {
    private static final int REQUEST_SELECT_INTEREST = 1001;
    private static final int REQUEST_PICK_IMAGE = 1002;
    private static final int REQUEST_PERMISSION = 1003;
    
    private de.hdodenhof.circleimageview.CircleImageView ivAvatar;
    private TextView tvUsername;
    private TextView tvInterest;
    private Button btnSelectInterest;
    private Button btnMyBooks;
    private Button btnLogout;
    
    private String username;
    private String interest;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        
        // 初始化控件
        ivAvatar = view.findViewById(R.id.iv_avatar);
        tvUsername = view.findViewById(R.id.tv_username);
        tvInterest = view.findViewById(R.id.tv_interest);
        btnSelectInterest = view.findViewById(R.id.btn_select_interest);
        btnMyBooks = view.findViewById(R.id.btn_my_books);
        btnLogout = view.findViewById(R.id.btn_logout);
        
        // 设置点击事件
        ivAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImagePicker();
            }
        });
        
        btnSelectInterest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到兴趣选择页面
                Intent intent = new Intent(getActivity(), InterestSelectActivity.class);
                startActivityForResult(intent, REQUEST_SELECT_INTEREST);
            }
        });
        
        btnMyBooks.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到书籍管理页面
                if (getActivity() != null) {
                    Intent intent = new Intent(getActivity(), BookManagerActivity.class);
                    intent.putExtra("user_email", username);
                    startActivity(intent);
                }
            }
        });
        
        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLogoutDialog();
            }
        });
        
        return view;
    }
    
    @Override
    public void onResume() {
        super.onResume();
        // 每次Fragment可见时重新加载头像
        loadUserAvatar();
    }
    
    /**
     * 显示图片选择器
     */
    private void showImagePicker() {
        if (getActivity() == null) return;
        
        // 检查存储权限
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) 
                != PackageManager.PERMISSION_GRANTED) {
            // 显示权限说明对话框
            new AlertDialog.Builder(getActivity())
                    .setTitle("需要存储权限")
                    .setMessage("应用需要存储权限才能从相册选择图片作为头像")
                    .setPositiveButton("去授权", (dialog, which) -> {
                        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION);
                    })
                    .setNegativeButton("取消", null)
                    .show();
        } else {
            // 直接打开相册
            openGallery();
        }
    }
    
    /**
     * 打开系统相册
     */
    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_PICK_IMAGE);
    }
    
    /**
     * 更新用户信息
     */
    public void updateUserInfo(String username, String interest) {
        this.username = username;
        this.interest = interest;
        if (tvUsername != null && tvInterest != null) {
            tvUsername.setText("用户名：" + username);
            tvInterest.setText("当前兴趣：" + interest);
        }
        
        // 加载用户头像
        loadUserAvatar();
    }
    
    /**
     * 加载用户头像
     */
    private void loadUserAvatar() {
        if (ivAvatar != null && username != null && !username.isEmpty()) {
            Bitmap avatarBitmap = AvatarManager.loadAvatar(requireContext(), username);
            if (avatarBitmap != null) {
                // 显示用户自定义头像
                ivAvatar.setImageBitmap(AvatarManager.getRoundedBitmap(avatarBitmap));
            } else {
                // 显示默认头像
                ivAvatar.setImageResource(R.drawable.default_avatar);
            }
        }
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_SELECT_INTEREST && data != null) {
                // 接收回传的兴趣数据
                String selectedInterest = data.getStringExtra("interest");
                if (selectedInterest != null && !selectedInterest.isEmpty()) {
                    this.interest = selectedInterest;
                    if (tvInterest != null) {
                        tvInterest.setText("当前兴趣：" + selectedInterest);
                    }
                    
                    // 通知宿主Activity更新首页Fragment
                    if (getActivity() != null) {
                        ((OnInterestSelectedListener) getActivity()).onInterestSelected(selectedInterest);
                    }
                }
            } else if (requestCode == REQUEST_PICK_IMAGE && data != null) {
                // 处理选择的图片
                handleImageResult(data);
            }
        }
    }
    
    /**
     * 处理图片选择结果
     * @param data Intent数据
     */
    private void handleImageResult(Intent data) {
        Uri imageUri = data.getData();
        if (imageUri != null && username != null) {
            try {
                // 从Uri获取图片输入流
                InputStream inputStream = requireContext().getContentResolver().openInputStream(imageUri);
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                
                if (bitmap != null) {
                    // 压缩图片到合适尺寸
                    Bitmap compressedBitmap = AvatarManager.compressBitmap(bitmap, 500, 500);
                    
                    // 保存头像
                    if (AvatarManager.saveAvatar(requireContext(), compressedBitmap, username)) {
                        // 更新界面显示
                        ivAvatar.setImageBitmap(AvatarManager.getRoundedBitmap(compressedBitmap));
                        Toast.makeText(getContext(), "头像更换成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getContext(), "头像保存失败", Toast.LENGTH_SHORT).show();
                    }
                    
                    // 回收Bitmap
                    if (bitmap != compressedBitmap) {
                        compressedBitmap.recycle();
                    }
                    bitmap.recycle();
                } else {
                    Toast.makeText(getContext(), "无法加载选中的图片", Toast.LENGTH_SHORT).show();
                }
                
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getContext(), "图片处理失败", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getContext(), "图片处理异常", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == REQUEST_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限授予，打开相册
                openGallery();
            } else {
                // 权限拒绝，显示提示
                Toast.makeText(getContext(), "未获得存储权限，无法选择图片", Toast.LENGTH_LONG).show();
            }
        }
    }
    
    /**
     * 显示退出登录确认对话框
     */
    private void showLogoutDialog() {
        if (getActivity() != null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(R.string.confirm_logout);
            builder.setMessage(R.string.logout_message);
            builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
                // 清除登录信息并返回登录页面
                SharedPreferences sharedPreferences = getActivity().getSharedPreferences("user_info", Activity.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.clear();
                editor.apply();

                // 跳转到登录页面
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                
                if (getActivity() != null) {
                    getActivity().finish();
                }
            });
            builder.setNegativeButton(R.string.cancel, (dialog, which) -> {
                // 取消对话框
                dialog.dismiss();
            });
            builder.show();
        }
    }
    
    /**
     * 兴趣选择回调接口
     */
    public interface OnInterestSelectedListener {
        void onInterestSelected(String interest);
    }
}